<script lang="ts" setup>
import { ref, onMounted } from "vue"
import { deleteTableDataApi, getTableDataApi, saveTableDataApi } from "@/api/course/classify"
import { type TableData, type CreateOrUpdateTableRequestData } from "@/api/course/types/classify"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { cloneDeep } from "lodash-es"

defineOptions({
  // 命名当前组件
  name: "courseClassify"
})

const loading = ref<boolean>(false)

//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateTableRequestData = {
  id: 0,
  title: "",
  pid: 0,
  is_use: 10
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateTableRequestData>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<CreateOrUpdateTableRequestData> = {
  title: [{ required: true, trigger: "blur", message: "分类标题不能为空" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    saveTableDataApi(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
//#endregion

//#region 删
const handleDelete = (row: TableData) => {
  ElMessageBox.confirm(`正在删除分类：${row.title}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi({ id: row.id }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion
const handleAddTwo = (row: TableData) => {
  console.log(row)
  dialogVisible.value = true
  const data = {
    id: 0,
    title: "",
    pid: row.id,
    is_use: 10
  }
  formData.value = cloneDeep(data)
}

//#region 改
const handleUpdate = (row: TableData) => {
  dialogVisible.value = true
  console.log(row)
  formData.value = cloneDeep(row)
}
//#endregion

//#region 查
const tableData = ref<TableData[]>([])
const CidOne = ref<TableData[]>([])
const getTableData = () => {
  loading.value = true
  getTableDataApi()
    .then((data) => {
      tableData.value = data
      CidOne.value = data.filter((item) => item.pid === 0)
    })
    .catch(() => {
      tableData.value = []
      CidOne.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
//#endregion

onMounted(() => {
  getTableData()
})
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增一级分类</el-button>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" row-key="id" default-expand-all>
          <el-table-column prop="title" label="分类名称" align="left" />
          <el-table-column prop="is_use" label="状态" align="center" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.is_use == 10" type="success" effect="plain">启用</el-tag>
              <el-tag v-else type="danger" effect="plain">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200" align="right">
            <template #default="scope">
              <el-button type="warning" v-if="scope.row.pid == 0" bg size="small" @click="handleAddTwo(scope.row)">
                添加
              </el-button>
              <el-button type="primary" bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id === undefined ? '新增一级分类' : '修改'"
      @closed="resetForm"
      width="500px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="pid" label="选择分类" required>
          <el-select v-model="formData.pid" placeholder="Select" size="large">
            <el-option label="顶级分类" :value="0" />
            <el-option v-for="item in CidOne" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="title" label="分类名称">
          <el-input v-model="formData.title" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item prop="is_use" label="分类状态" required>
          <el-select v-model="formData.is_use" placeholder="选择状态">
            <el-option label="启用" :value="10" />
            <el-option label="禁用" :value="20" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
